package com.zf.websocket.handle;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;

import java.util.concurrent.ConcurrentHashMap;

/**
 * 简单群聊系统
 */
@Component
public class ChatHandler extends AbstractWebSocketHandler {
    public static final ConcurrentHashMap<String, WebSocketSession> USERS = new ConcurrentHashMap<>();

    /**
     * 建立连接后执行
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        USERS.put(session.getId(), session);
    }

    /**
     * 处理文本消息
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        for (WebSocketSession webSocketSession : USERS.values()) {
                if (session == webSocketSession) {
                    // 回显消息给自己
                    session.sendMessage(new TextMessage("[我] " + message.getPayload()));
                } else {
                    //发送给其他在线用户
                    webSocketSession.sendMessage(new TextMessage(String.format("[%s] %s", session.getId(), message.getPayload())));
                }
        }
    }

    /**
     * 消息传输过程中出错后执行
     */
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        System.out.println(session.getId() + " 消息出错: " + exception);
    }

    /**
     * 断开连接后执行
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        USERS.remove(session.getId());
    }
}
